// Ninf-G-XX, ver. 0.1
// Copyright 2011 National Institute of Advanced Industrial Science and Technology
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#define _XOPEN_SOURCE /* glibc2 needs this */
#include <time.h>
//#define __USE_BSD
#include <string.h>

#include <stdio.h>
#include <unistd.h>
#include "LogParser.hpp"
#include "Exception.hpp"
#include "Global.hpp"

using namespace ninf::client;
LogParser :: LogParser(int pid)
: filename(NULL), fp(NULL), pid(pid)
{
}

void
LogParser :: open(){
  if (filename == NULL){
    char buffer [1000];
    sprintf(buffer, "%s/log", Global::global.runDir);
    filename = strdup(buffer);
  }
  if (fp == NULL)
    fp = fopen(filename, "r");
}


static void
myfgets(char * buffer, int len, FILE * fp){
  while (true) {
    char * tmp = fgets(buffer, len, fp);
//    fprintf(stderr, "%s", tmp);
    if (tmp != NULL)
      break;
    if (ferror(fp))
      throw Exception("fgets failed!", __FILE__, __LINE__);
    clearerr(fp);
    fprintf(stderr, "go to sleep\n");
    sleep(10);
    fprintf(stderr, "wake up\n");
  }
}


LogEntry
LogParser :: parse(){
  open();
  if (fp == NULL)
    EXCEPTION(string("failed to open log file: ") + filename);

  LogEntry entry;
  char buffer[1000];
  myfgets(buffer, 1000, fp);

  buffer[strlen(buffer) - 1] = '\0';
  *(buffer + 17) = '\0';

  sscanf(buffer, "%d (%d.%d.%d)",
	 &(entry.statusCode),
	 &(entry.jobId0),
	 &(entry.jobId1),
	 &(entry.jobId2));
  int counter = 0;
  char * pointer = buffer + 18;
  while (counter < 2){
    if (*pointer == ' ')
      counter++;
    pointer++;
  }
  *(pointer-1) = '\0';
  strptime(buffer + 18, "%m/%d %T", &(entry.time));

  entry.setMessage(pointer);

  // skip lines till "..."

  while (true){
    myfgets(buffer, 1000, fp);
    if (strncmp(buffer, "...\n", 5) == 0)
      break;
  }
  return entry;
}
